﻿using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.Conditions;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.Workflows
{
    /// <summary>
    /// 节点映射
    /// </summary>
    public class NodeMap
    {
        /// <summary>
        /// 节点类型
        /// </summary>
        public NodeMapType MapType { get; set; }
        /// <summary>
        /// 起始节点
        /// </summary>
        public WorkflowNode FromNode { get; set; }
        /// <summary>
        /// 目标节点
        /// </summary>
        public WorkflowNode ToNode { get; set; }
        /// <summary>
        /// 连接条件
        /// </summary>
        public List<LineCondition> Conditions { get; set; }

        /// <summary>
        /// 是否能接受
        /// 根据条件参数解析判断是否能派发到该节点
        /// </summary>
        /// <param name="workTask"></param>
        /// <returns></returns>
        public bool CanAccept(WorkTask workTask, WorkStep currentWorkStep, ConditionManager conditionManager)
        {
            if (Conditions == null) return true;
            foreach (var condition in Conditions)
            {
                var conditioncondition = conditionManager.GetCondition(condition.ConditionId);
                if (conditioncondition == null) continue;
                var can = conditioncondition.CanAccept(new ConditionInput
                {
                    Expression = condition.Parameter,
                    WorkTask = workTask,
                    CurrentWorkStep= currentWorkStep
                });
                //如果有一个是否的，就直接返回false
                if (!can) return false;
            }
            return true;
        }

        public enum NodeMapType
        {
            /// <summary>
            /// 普通节点
            /// </summary>
            Normal,
            /// <summary>
            /// 驳回节点
            /// </summary>
            Reject
        }

        public class  Factory
        {
            private static NodeMap NewNodeMap(WorkflowNode FromNode, WorkflowNode ToNode, List<LineCondition> Conditions)
            {
                var map = new NodeMap();
                map.FromNode = FromNode;
                map.ToNode = ToNode;
                map.Conditions = Conditions;
                return map;
            }

            public static NodeMap NewNormalNodeMap(WorkflowNode FromNode, WorkflowNode ToNode, List<LineCondition> Conditions)
            {
                var map = NewNodeMap(FromNode,ToNode,Conditions);
                map.MapType = NodeMapType.Normal;
                return map;
            }
            public static NodeMap NewRejectNodeMap(WorkflowNode FromNode, WorkflowNode ToNode, List<LineCondition> Conditions)
            {
                var map = NewNodeMap(FromNode, ToNode, Conditions);
                map.MapType = NodeMapType.Reject;
                return map;
            }
        }
    }
}
